package com.zrt.utils.excel.listener;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

/**
 * @author 庄锐涛
 */
public class ExcelListener extends AnalysisEventListener {

    private List<Object> dataList = new ArrayList<>();


    @Override
    public void invoke(Object o, AnalysisContext analysisContext) {
        if (checkObjAllFieldsIsNull(o)) {
            dataList.add(o);
        }
    }

    /**
     * 解析完excel文件后
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //do something
    }

    /**
     * 判断对象中属性值是否全为空
     */
    private static boolean checkObjAllFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                //只校验带ExcelProperty注释的属性
                ExcelProperty property = f.getAnnotation(ExcelProperty.class);
                if (property == null) {
                    continue;
                }
                if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
                    return false;
                }
            }
        } catch (Exception e) {
            //do something
        }
        return true;
    }

    public List<Object> getDataList() {
        return dataList;
    }

}
